//
//  NFCViewController.m
//  objective_c_language
//
//  Created by 王玉龙 on 2018/6/10.
//  Copyright © 2018年 longlong. All rights reserved.
//

#import "NFCViewController.h"
#import <CoreNFC/CoreNFC.h>

@interface NFCViewController ()
<NFCNDEFReaderSessionDelegate>

@end

@implementation NFCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (@available(iOS 11.0, *)) {
        
        dispatch_queue_t testQueue = dispatch_queue_create("com.objective_c_language.NFC.test", DISPATCH_QUEUE_CONCURRENT);

        NFCNDEFReaderSession *session = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:testQueue invalidateAfterFirstRead:YES];
        [session beginSession];

    } else {
        // Fallback on earlier versions
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 处理协议回调方法
#pragma mark - NFCReaderSessionDelegate
// Check invalidation reason from the returned error. A new session instance is required to read new tags.
// 识别出现Error后会话会自动终止，此时就需要程序重新开启会话
- (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error  API_AVAILABLE(ios(11.0)){
    // error明细参考NFCError.h
    NSLog(@"session错误 ： %@",error);
}

// Process detected NFCNDEFMessage objects
- (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray<NFCNDEFMessage *> *)messages API_AVAILABLE(ios(11.0))
{
    NSLog(@"session : %@", session);
    NSLog(@"messages : %@", messages);

    // 数组messages中是NFCNDEFMessage对象
    // NFCNDEFMessage对象中有一个records数组，这个数组中是NFCNDEFPayload对象
    // 参考NFCNDEFMessage、NFCNDEFPayload类
    // 解析数据
    for (NFCNDEFMessage *message in messages) {
        for (NFCNDEFPayload *playLoad in message.records) {
            NSLog(@"typeNameFormat : %d", playLoad.typeNameFormat);
            NSLog(@"type : %@", playLoad.type);
            NSLog(@"identifier : %@", playLoad.identifier);
            NSLog(@"playload : %@", playLoad.payload);
        }
    }
}




@end
